package cn.yilongquan.controller;

import cn.yilongquan.service.ParamService;
import cn.yilongquan.system.domain.Param;
import cn.yilongquan.system.query.ParamQuery;
import cn.yilongquan.util.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/param")
@ResponseBody
public class ParamController {
    @Resource
    private ParamService paramService;


    // 修复上传接口
    @PostMapping("/addWithImg")
    public R addWithImg(
            @RequestParam("paramKey") String paramKey,
            @RequestParam("type") Integer type,
            @RequestParam("operatorName") String operatorName,
            @RequestParam(value = "paramDesc", required = false) String paramDesc,
            @RequestParam("imgFile") MultipartFile imgFile) {

        try {
            Param param = new Param();
            param.setParamKey(paramKey);
            param.setType(type);
            param.setOperatorName(operatorName);
            param.setParamDesc(paramDesc);

            paramService.addWithImg(param, imgFile);
            return R.ok("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("添加失败：" + e.getMessage());
        }
    }

    // 分页查询
    @PostMapping("/list")
    public R list(@RequestBody ParamQuery query) {
        List<Param> list = paramService.findPage(query);
        int total = paramService.total(query);

        // 创建一个Map存储分页数据
        Map<String, Object> result = new HashMap<>();
        result.put("data", list);
        result.put("total", total);

        // 使用R.ok()方法返回包含分页数据的响应
        return R.ok(result);
    }

    // 新增
    @PostMapping("/add")
    public R add(@RequestBody Param param) {
        paramService.add(param);
        return R.ok();
    }

    // 修改
    @PostMapping("/update")
    public R update(@RequestBody Param param) {
        paramService.update(param);
        return R.ok();
    }

    // 删除
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        paramService.delete(id);
        return R.ok();
    }

    // 批量删除
    @PostMapping("/deleteAll")
    public R deleteBatch(@RequestBody Long[] ids) {
        paramService.deleteBatch(ids);
        return R.ok();
    }


}